﻿/**
 * Created by Eason on 2014/12/17.
 */
const iOS = 1;
const Android = 2;
const Browser = 3;
var reload = false;
$(function () {
    switch (mc.device) {
        case iOS:
        {
            FastClick.attach(document.body);// 去掉300毫秒延迟
            break;
        }
        case Android:
            mc.hideStatusBarInAndroid();
            FastClick.attach(document.body);// 去掉300毫秒延迟
            break;
        case Browser:
        {
            document.body.addEventListener('touchstart', function () {
            });
            FastClick.attach(document.body);// 去掉300毫秒延迟
            basic.deviceReady();
            basic.viewDidAppearCallback();
            break;
        }
    }
});
(function () {
    mc.device = undefined;
    var URL = window.location.toString();
    var isBrowser = (URL.indexOf("http://") > -1 && mc.developer == false);//浏览器
    var isApp = (URL.indexOf("http://") == -1 || mc.developer == true);//App
    function errorHandler(e){
        var error = 'error: '+ e.message+'\n file: '+ e.filename+'\n line: '+ e.lineno;
        //alert(error);
    }
    window.addEventListener("error",errorHandler,false);
    if (isBrowser) {//浏览器
        mc.device = Browser;
        document.write("<style>.mc-btn,.mc-responseicon{-webkit-transition: background-color,font-size,color,-webkit-filter;-webkit-transition-timing-function: linear;-webkit-transition-duration: .12s;}</style>");
    }
    else if (isApp) {//App
        var navigatorDevice = navigator.userAgent;
        var isiOS = !!navigatorDevice.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);//iOS
        var isAndroid = navigatorDevice.indexOf("Android") > -1;//Android
        if (isiOS) {//iOS
            mc.device = iOS;
            //引入IOS cordova和其他JS
            document.write("<script src='cordova_iOS.js'></script>" +
                "<script src='Tools/MoCoop/factory/interfaceOfiOS/CommunicationBetweeniOSAndWeb.js'></script>"
                //+"<style>.mc-btn,.mc-responseicon{-webkit-transition: background-color,font-size,color,-webkit-filter;-webkit-transition-timing-function: linear;-webkit-transition-duration: .12s;}</style>"
            );
        }
        else if (isAndroid) {//Android
            mc.device = Android;
            //引入Android cordova和其他JS
            document.write("<script src='cordova_Android.js'></script>" +
                "<script src='Tools/MoCoop/factory/interfaceOfAndroid/CommunicationBetweenAndroidAndWeb.js'></script>"//Android
            );
        }

        document.addEventListener("deviceready", function () {
            if (reload) {
                return
            }
            basic.deviceReady();
        }, false);
    }
    ////基础方法
    //原生跨域请求
    mc.beginAsyncAjax = function (ajaxURL, ajaxData, ajaxType, callback, timeOut) {
        switch (mc.device) {
            case iOS:
                var options = {
                    "timeOut": timeOut / 1000
                };
                beginAsyncAjax(ajaxURL, ajaxData, ajaxType, function (data) {
                    if (data.result == true) {
                        try {
                            var result = JSON.parse(data.response);
                        } catch (err) {
                            result = data.response;
                        }
                        callback(result);
                    } else {
                        try {
                            var error = JSON.parse(data.error);
                        } catch (err) {
                            error = data.error;
                        }
                        callback(error);
                    }
                }, options);
                break;
            case Android:
                var options = {
                    "timeOut": timeOut / 1000
                };
                beginAsyncAjax(ajaxURL, ajaxData, ajaxType, function (data) {
                    callback(data);
                }, options);
                break;
            case Browser:
                var data = {
                    url: ajaxURL,
                    data: ajaxData,
                    method: ajaxType
                };
                $.ajax({
                    url: './tps/ajaxRequest',
                    data: JSON.stringify(data),
                    type: "POST",
                    contentType: "application/json",
                    "Content-Type": "utf-8",
                    async: true,
                    dataType: "json",
                    success: callback,
                    error: callback
                });
                break;
        }
    };
    mc.showContent = function () {
        switch (mc.device) {
            case iOS:
            case Android:
                showMeRightNow();
                break;
        }

    };
    //设置setUserID
    mc.setUserID = function (userID, callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                setUserID(userID, callback);
                break;
            case Browser:
                callback();
                break;
        }
    };
    //清除userID
    mc.removeUserID = function (callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                removeStoredUserID(callback);
                break;
            case Browser:
                callback();
                break;
        }
    };
    //保存数据到平台存储
    mc.saveDataToLocalStorage = function (key, value, callback, secret) {
        var from;
        switch (mc.device) {
            case iOS:
            {
                if (secret != undefined) {
                    if (secret == "app") {
                        from = SecretDataSourceType.App;
                    } else if (secret == "user") {
                        from = SecretDataSourceType.User;
                    }
                    setSecretData(from, key, value, function (data) {
                        if (data.result == true) {
                            callback(true)
                        } else {
                            callback(false)
                        }
                    });
                } else {
                    setPermanentData(key, value, callback);
                }
                break;
            }
            case Android:
                var type;
                if (secret == "app") {
                    type = "public";
                } else if (secret == "user") {
                    type = "private";
                } else {
                    type = "private";
                }
                if (typeof value != "string") {
                    value = JSON.stringify(value)
                } else {
                    value = "\"" + value + "\"";
                }
                //alert(value + "-------23131")
                //console.log(value);
                saveToSharedPreferences(type, key, value, function (data) {
                    callback(data)
                });
                break;
            case Browser:
            {
                window.localStorage.setItem(key, value);
                if (callback != null && callback != undefined) {
                    callback()
                }
                break;
            }
        }
    };
    //从平台存储中获取数据
    mc.getDataFromLocalStorage = function (key, callback, secret) {
        var from;
        switch (mc.device) {
            case iOS:
            {
                if (secret != undefined) {

                    if (secret == "app") {
                        from = SecretDataSourceType.App;
                    } else if (secret == "user") {
                        from = SecretDataSourceType.User;
                    }
                    getSecretData(from, key, function (data) {
                        if (data.result == true) {
                            callback(data.secretData)
                        } else {
                            //developerAlert("获取‘"+key+"’失败；失败原因："+data.error);
                            callback();
                        }
                    });
                } else {
                    getPermanentData(key, function (data) {
                        if (data.result == true) {
                            callback(data.permanentData)
                        } else {
                            //developerAlert(data.error);
                            callback();
                        }
                    });
                }
                break;
            }
            case Android:
                var type;
                if (secret == "app") {
                    type = "public";
                } else if (secret == "user") {
                    type = "private";
                } else {
                    type = "private";
                }
                findSharedPreferences(type, key, function (data) {
                    if(data != "NULL") {
                        data = JSON.parse(data);
                        /*if (data.result == true) {
                         try {
                         data.data = JSON.parse(data.data)
                         } catch (e) {
                         }
                         callback(data.data)
                         } else {
                         callback();
                         }*/
                        callback(data)
                    } else {
                        callback(null);
                    }
                });
                break;
            case Browser:
            {
                var returnData = localStorage.getItem(key);
                callback(returnData);
                break;
            }
        }
    };

    //删除平台存储中的指定数据
    mc.deleteDataFromLocalStorage = function (key, secret) {
        switch (mc.device) {
            case iOS:
            {
                if (secret != undefined) {
                    var from;
                    if (secret == "app") {
                        from = SecretDataSourceType.App;
                    } else if (secret == "user") {
                        from = SecretDataSourceType.User;
                    }
                    removeSecretData(from, key, null);
                } else {
                    removePermanentData(key, null);
                }
                break;
            }
            case Android:
                var from;
                if (secret == "app") {
                    from = 0;
                } else if (secret == "user") {
                    from = 2;
                } else {
                    from = 1;
                }
                removeData(key, from);
                break;
            case Browser:
                localStorage.removeItem(key);
                break;
        }
    };

    //清除平台存储中的所有数据
    mc.clearAllDataInLocalStorage = function () {
        switch (mc.device) {
            case iOS:
                clearPermanentDatas();
                clearSecretDatas(SecretDataSourceType.App);
                clearSecretDatas(SecretDataSourceType.User);
                break;
            case Android:
                clearData(0);
                clearData(1);
                clearData(2);
                break;
            case Browser:
                localStorage.clear();
                break;
        }
    };
    //获取登录人信息
    mc.getUserInfo = function (callback) {
        /*var getUserInfoCallback = function (data) {
            if (data.result == true) {
                vars.userInfo = JSON.parse(data.secretData);
                if (callback != null && callback != undefined) {
                    callback()
                }
            }
        };
        mc.getDataFromLocalStorage("userInfo", getUserInfoCallback, true)*/
        switch (mc.device) {
            case iOS:
            case Android:
                getUserInfo(callback);
                break;
            case Browser:
                callback();
                break;
        }

    };

    mc.setAppMode = function (value, callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                setAppMode(value, callback);
                break;
        }
    };

    mc.getAppMode = function (callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                getAppMode(callback);
                break;
        }
    };

    //退出登录
    mc.logOutUser = function (callback) {
        /*var getUserInfoCallback = function (data) {
            if (data.result == true) {
                vars.userInfo = JSON.parse(data.secretData);
                if (callback != null && callback != undefined) {
                    callback()
                }
            }
        };
        mc.getDataFromLocalStorage("userInfo", getUserInfoCallback, true)*/
        switch (mc.device) {
            case iOS:
            case Android:
                logOutUser(callback);
                break;
            case Browser:
                callback();
                break;
        }

    };
    //跳转到新页面
    mc.jump = function (pageURL, topBarTitle, type, shouldKillForwardPages) {
        switch (mc.device) {
            case iOS: {
                var pageJumpsInfo = {
                    pathSuffix: pageURL,
                    type: "Direct",
                    showType: "Push",
                    animated: true,
                    title: topBarTitle,
                    configFileSubPath: "config/theme-page.json"
                };
                if (shouldKillForwardPages != undefined) {
                    if (shouldKillForwardPages == "all") {
                        pageJumpsInfo.shouldKillForwardPages = true
                    } else if (typeof shouldKillForwardPages == "number") {
                        pageJumpsInfo.killForwardPageCount = shouldKillForwardPages
                    }
                }
                if (type == "Normal") {
                    pageJumpsInfo.type = type;
                    delete pageJumpsInfo.animated;
                    delete pageJumpsInfo.title;
                    delete pageJumpsInfo.configFileSubPath
                }
                if (type == "Modal") {
                    pageJumpsInfo.showType = "Present";
                    pageJumpsInfo.configFileSubPath = "config/theme-pagePresent.json"
                }
                if (type == "SubmitModal") {
                    pageJumpsInfo.showType = "Present";
                    pageJumpsInfo.configFileSubPath = "config/theme-pagePresentSubmit.json"
                }
                if (mc.developer == true) {
                    pageJumpsInfo.basedURL = mc.jumpURL;
                }
                jumpToPage(pageJumpsInfo);
                break;
            }
            case Android:
            {
                var pageJumpsInfo = {
                    URL: pageURL,
                    type: "Direct",
                    showType: "Push",
                    animated: true,
                    topBarTitle: topBarTitle,
                    UIFeatureJSONFileSubPath: "config/theme-page.json"
                };
                if (shouldKillForwardPages != undefined) {
                    if (shouldKillForwardPages == "all") {
                        pageJumpsInfo.shouldKillForwardPages = true
                    } else if (typeof shouldKillForwardPages == "number") {
                        pageJumpsInfo.killForwardPageCount = shouldKillForwardPages
                    }
                }
                if (type == "Normal") {
                    pageJumpsInfo.type = type;
                    delete pageJumpsInfo.animated;
                    delete pageJumpsInfo.topBarTitle;
                    delete pageJumpsInfo.UIFeatureJSONFileSubPath
                }
                if (type == "Modal") {
                    pageJumpsInfo.showType = "Present";
                    pageJumpsInfo.UIFeatureJSONFileSubPath = "config/theme-pagePresent.json"
                }
                if (type == "SubmitModal") {
                    pageJumpsInfo.showType = "Present";
                    pageJumpsInfo.UIFeatureJSONFileSubPath = "config/theme-pagePresentSubmit.json"
                }
                if (mc.developer == true) {
                    pageJumpsInfo.URL = mc.jumpURL + pageURL;
                }
                if (pageURL == "login.html") {
                    delete pageJumpsInfo.topBarTitle;
                    delete pageJumpsInfo.UIFeatureJSONFileSubPath
                }
                jumpToPage(pageJumpsInfo);
                break;
            }
            case Browser:
                window.location.href = pageURL;
                break;
        }
    };
    //返回上一页
    mc.backToPrePage = function () {
        switch (mc.device) {
            case iOS:
                backToForwardPage(true);
                break;
            case Android:
                backToForwardPage();
                break;
            case Browser:
                window.history.go(-1);
                break;
        }
    };
    //回到指定页面
    mc.backToTargetPage = function (pageURL) {
        switch (mc.device) {
            case iOS:
                break;
            case Android:
                backToTargetPage(pageURL);
                break;
            case Browser:
                window.location.href = pageURL;
                break;
        }
    };
    //将页面显示到主屏幕
    mc.putPageIntoMainScreen = function () {
        switch (mc.device) {
            case iOS:
            case Android:
            {
                putMeIntoMainScreen();
                break;
            }
        }
    };

    //安卓控制实体返回键
    mc.backContorlOfAndroid = function (action) {
        switch (mc.device) {
            case iOS:
                break;
            case Android:
                backContorl(action);
                break;
            case Browser:
                break;
        }
    };
    //获取网络状态
    mc.getNetworkStatus = function (callback) {
        switch (mc.device) {
            case iOS:
                var networkState = navigator.connection.type;
                if ((networkState == Connection.UNKNOWN) || (networkState == Connection.NONE)) {
                    // 无网络
                    callback({result: false});
                } else {
                    // 有网络
                    callback({result: true});
                }
                break;
            case Android:
                isNetworkConnected(callback);
                break;
            case Browser:
                callback({result: true});
                break;
        }
    };
    // 普通 "Normal";
    // 进度 "Progress";
    // 成功 "Succeed";
    // 失败  "Failed";
    // Info  "Info";
    //提示
    mc.notification = function (message, type, progress) {
        switch (mc.device) {
            case iOS:
                if (type != "Close") {
                    var info = {
                        text: message,
                        progress: progress,
                        type: type
                    };
                    showHUD(info, null);
                } else {
                    dismissHUD(null)
                }
                break;
            case Android:
                if (type != "Close") {
                    showPop(message, type, progress);
                } else {
                    hidePop()
                }
                break;
            case Browser:
                break;
        }
    };

    mc.actionSheet = function (callback, title, arrOtherBtnItemTitles, destructiveBtnItemTitle, cancelBtnItemTitle, fromRect) {
        switch (mc.device) {
            case iOS:
                showActionSheet(callback, title, arrOtherBtnItemTitles, destructiveBtnItemTitle, cancelBtnItemTitle, fromRect);
                break;
            case Android:
                actionSheet(title, arrOtherBtnItemTitles, function (data) {
                    callback({chosenActionTitle: data})
                });
                break;
            case Browser:
                break;
        }
    };
    mc.setKeyboardScrollDisable = function () {
        if (mc.device == iOS) {
            cordova.plugins.Keyboard.disableScroll(true);
        }
    };

    ////扩展功能
    //检查更新
    mc.checkUpdate = function () {
        switch (mc.device) {
            case iOS:
                checkUpdatableVersion(null);
                break;
            case Android:
                checkUpgrade();
                break;
            case Browser:
                break;
        }
    };
    mc.getAppVersion = function (callback) {
        switch (mc.device) {
            case iOS:
                getAppVersion(callback);
                break;
            case Android:
                getNowVersion(function (data) {
                    callback({appVersion: data})
                });
                break;
            case Browser:
                break;
        }
    };
    mc.execSQL = function (sql, params, callback) {
        switch (mc.device) {
            case iOS:
                var execSQLCallback = function(data){
                    if(data.result === true){
                        callback(data.dataSet)
                    }else{
                        mc.alert(data.error)
                    }
                };
                var judgeSQLType = sql.toLowerCase().indexOf("select");
                var isQuerySQL = judgeSQLType === 0 ? (true) : (false);
                if(isQuerySQL === true){//如果为查询 执行查询SQL方法
                    queryUserDataCenter(sql, params, execSQLCallback);
                }else{//如果为操作 执行操作SQL方法
                    updateUserDataCenter(sql, params, execSQLCallback);
                }
                break;
            case Android:
                execSQL(sql, params, callback);
                break;
            case Browser:
                break;
        }
    };
    mc.openCamera = function (callback) {
        switch (mc.device) {
            case iOS:

                break;
            case Android:
                getPhotos(callback);
                break;
            case Browser:
                break;
        }
    };
    mc.submitToAjaxWorker = function (params, callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                submitToAjaxWorker(params, callback);
                break;
            case Browser:
                break;
        }
    };
    mc.syncData = function (tables, callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                syncData(tables, callback);
                break;
            case Browser:
                break;
        }
    };
    mc.uploadAjaxTask = function (ajaxIDs, callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                uploadAjaxTask(ajaxIDs, callback);
                break;
            case Browser:
                break;
        }
    };
    mc.uploadAllAjaxTask = function (callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                uploadAllAjaxTask(callback);
                break;
            case Browser:
                break;
        }
    };
    mc.downloadPhoto = function (photosKey, callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                downloadPhoto(photosKey, callback);
                break;
            case Browser:
                break;
        }
    };
    mc.getPhotosProgress = function(callback){
        switch (mc.device) {
            case iOS:
            case Android:
                getPhotosProgress(callback);
                break;
            case Browser:
                break;
        }
    }
    mc.showPhotosByIndex = function(photosKeys, currIndex, callback){
        switch (mc.device) {
            case iOS:
                checkLocalImages(photosKeys, currIndex, false, callback);
                break;
            case Android:
                openPhotoBrowse(photosKeys,currIndex,callback);
                break;
            case Browser:
                break;
        }
    };
    mc.getMessageCount = function (type, count, callback) {
        switch (mc.device) {
            case iOS:
                badgeMessage(type,count,callback);
                break;
            case Android:
                messageCountController(type, count, callback);
                break;
            case Browser:
                break;
        }
    }
    mc.myFileChooser = function (callback) {
        switch (mc.device) {
            case iOS:
                var photos = [];
                var actions = [{"title":"拍照","action":ActionType.Camera},
                    {"title":"从相册选择","action":ActionType.PhotoLibrary},
                    {"title":"取消","action":ActionType.Cancel}];
                var options={
                    multipleSelectionEnabled:true,
                    maxSelectionCount:10,
                    targetWidth:800,
                    targetHeight: 800
                };
                fetchImage(options,null,actions,function(data){
                    if(data.result == false|| data.info.canceled == true) {
                        return
                    }
                    console.log(data.info.imageFileURLs)
                    var dataArr=data.info.imageFileURLs;

                    var i = 0;
                    var graphicsOptimiserPhotoItem = function () {
                        var originalImgUrl = dataArr[i];
                        var options = {
                            imgURL: originalImgUrl,
                            width: 50,
                            height: 50
                        };
                        graphicsOptimiser(options, function (data) {
                            if(data.result == false) {
                                return;
                            }
                            var time = new Date().getTime();
                            var thumbnailImgUrl = data.thumbnailImgFilePath;
                            var imgName = thumbnailImgUrl.split("/")[thumbnailImgUrl.split("/").length - 1];
                            var imgNameArr = imgName.split(".");
                            var imgNameArrLength = imgName.split(".").length;
                            var extention = "."+imgNameArr[imgNameArrLength-1];
                            var photoItem = {
                                "originalFileKey": "" + time + extention,
                                "originalFilePath": originalImgUrl,
                                "thumbnailFileKey": "96x96_" + time + extention,
                                "thumbnailFilePath": thumbnailImgUrl
                            };
                            photos.push(photoItem);
                            i++;
                            if(i < dataArr.length){
                                graphicsOptimiserPhotoItem();
                            } else {
                                callback(photos);
                            }
                        });
                    }
                    graphicsOptimiserPhotoItem();

                });
                break;
            case Android:
                myFileChooser(callback);
                break;
            case Browser:
                break;
        }
    }
    mc.killLaunch = function (callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                killLaunch(callback);
                break;
            case Browser:
                break;
        }
    }

    // 清除缓存
    mc.clearCache = function (callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                clearCache(callback);
                break;
            case Browser:
                break;
        }
    }

})();
function developerAlert(message) {
    if (mc.developer == true) {
        if (message != undefined) {
            if (typeof message != "string") {
                message = JSON.stringify(message)
            }
            alert("调试信息 " + message)
        }
    }
}